package cn.lh.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.collect.Maps;

import java.util.Date;

/**
 * @描述:
 * @版权: Copyright (c) 2023
 * @作者: linhong
 * @版本: 1.0.0
 * @创建时间: 2023/12/29
 */
public class JWTUtil {

    private static final String privateKey = "null123";

    public static String createToken(Integer userId, String userName){
        DateTime date = DateUtil.date();
        DateTime endDate = DateUtil.offsetHour(date, -2);
        return JWT.create().withHeader(Maps.newHashMap())//表头可以省略
                .withClaim("userId",userId)
                .withClaim("userName",userName)
                .withIssuedAt(date)
//                .withExpiresAt(endDate)
                .sign(Algorithm.HMAC256(privateKey));
    }

    public static boolean verifyToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(privateKey)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        Integer userId = decodedJWT.getClaim("userId").asInt();
        String userName = decodedJWT.getClaim("userName").asString();
        Date expiresAt = decodedJWT.getExpiresAt();
        return true;
    }


    public static void main(String[] args) {
        String token = createToken(1, "zhangSan");
        verifyToken(token);
    }

}
